package com.chy.blog_web.modular.web.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chy.blog_web.core.util.GetUserIpAddressUtil;
import com.chy.blog_web.core.util.PageAndParamUtil;
import com.chy.blog_web.core.util.UploadFileUtil;
import com.chy.blog_web.core.util.UploadURLUtil;
import com.chy.blog_web.modular.system.entity.SysMenu;
import com.chy.blog_web.modular.system.service.ISysMenuService;
import com.chy.blog_web.modular.web.entity.*;
import com.chy.blog_web.modular.web.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * 描述：我的文章 controller
 * 作者：chenhuiyan
 * 时间：2020/03/06 22:07
 */
@Controller
@RequestMapping(value = "/myArticle")
public class MyArticleController {

    /**
     * 前缀
     */
    private static String PREFIX = "web/myArticle/";

    /**
     * 导航service
     */
    @Autowired
    private ISysMenuService sysMenuService;

    /**
     * 内容service
     */
    @Autowired
    private IBoContentService boContentService;

    /**
     * 相册service
     */
    @Autowired
    private IBoPhotoAlbumService boPhotoAlbumService;

    /**
     * 文章标签service
     */
    @Autowired
    private IBoTagService boTagService;

    /**
     * 文章service
     */
    @Autowired
    private IBoArticleService boArticleService;

    /**
     * 评论/留言service
     */
    @Autowired
    private IBoCommentService boCommentService;

    /**
     * 附件service
     */
    @Autowired
    private IBoFileService boFileService;

    /**
     * 跳转我的文章页面
     * @return
     */
    @RequestMapping(value = "")
    public String index(){
        return PREFIX + "myArticle";
    }

    /**
     * 查询导航、LOGO标题、页脚、我的相册、文章标签（关联的文章总数）、站长推荐文章、文章点击排行
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getMyArticleData")
    public Map<String, Object> getMyArticleData(){
        Map<String, Object> res = new HashMap<>();
        try{
            //查询前台显示导航，并且按创建时间升序排序
            List<SysMenu> sysMenuList = sysMenuService.getBaseMapper()
                    .selectList(new QueryWrapper<SysMenu>()
                            .eq("type", 1)
                            .eq("is_show", 0)
                            .eq("del_flag", 0)
                            .orderByAsc("sort"));

            //查询LOGO标题，编号为：521f1cd04f9d4345af2e62213178d6ac
            BoContent logoTitle = boContentService.getById("521f1cd04f9d4345af2e62213178d6ac");

            //查询页脚，编号为：5d8530c950d243e18e57b74190aa2d94
            BoContent indexFooter = boContentService.getById("5d8530c950d243e18e57b74190aa2d94");

            //查询友情连接，编号为：26cd46e996704076aea248ff9c3a90b9
            BoContent friendshipUrl = boContentService.getById("26cd46e996704076aea248ff9c3a90b9");

            //查询我的相册,设置为显示的、不上锁的、按创建时间降序排列,最多查6条
            List<BoPhotoAlbum> boPhotoAlbumList = boPhotoAlbumService.getBaseMapper()
                    .selectList(new QueryWrapper<BoPhotoAlbum>()
                            .eq("is_show", 0)
                            .eq("is_lock", 0)
                            .eq("del_flag", 0)
                            .orderByDesc("create_date")
                            .last("LIMIT 6"));

            //查询文章标签（关联的文章总数）
            List<Map<String , Object>> boTagList = boTagService.getBoTagList();

            //查询站长推荐、通过审核文章，按创建时间降序,最多查10条
            List<BoArticle> boArticleTopList = boArticleService.getBaseMapper()
                    .selectList(new QueryWrapper<BoArticle>()
                            .eq("is_top", 1)
                            .eq("is_pass", 1)
                            .eq("del_flag", 0)
                            .orderByDesc("create_date")
                            .last("LIMIT 10"));

            //文章点击排行、通过审核文章,按阅读、赞、时间排序。最多查10条
            List<BoArticle> articleClickList = boArticleService.getBaseMapper()
                    .selectList(new QueryWrapper<BoArticle>()
                            .eq("is_pass", 1)
                            .eq("del_flag", 0)
                            .orderByDesc("read_num")
                            .orderByDesc("praise_num")
                            .orderByDesc("create_date")
                            .last("LIMIT 10"));

            res.put("sysMenuList", sysMenuList);
            res.put("logoTitle", logoTitle);
            res.put("indexFooter", indexFooter);
            res.put("friendshipUrl", friendshipUrl);
            res.put("boPhotoAlbumList", boPhotoAlbumList);
            res.put("boTagList", boTagList);
            res.put("boArticleTopList", boArticleTopList);
            res.put("articleClickList", articleClickList);
            res.put("state", "200");
            res.put("message", "初始化成功");
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "服务器异常，请重新刷新页面！");
        }

        return res;
    }

    /**
     * 查询导航、LOGO标题、页脚
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getMyArticleInfoData")
    public Map<String, Object> getMyArticleInfoData(){
        Map<String, Object> res = new HashMap<>();
        try{
            //查询前台显示导航，并且按创建时间升序排序
            List<SysMenu> sysMenuList = sysMenuService.getBaseMapper()
                    .selectList(new QueryWrapper<SysMenu>()
                            .eq("type", 1)
                            .eq("is_show", 0)
                            .eq("del_flag", 0)
                            .orderByAsc("sort"));

            //查询LOGO标题，编号为：521f1cd04f9d4345af2e62213178d6ac
            BoContent logoTitle = boContentService.getById("521f1cd04f9d4345af2e62213178d6ac");

            //查询页脚，编号为：5d8530c950d243e18e57b74190aa2d94
            BoContent indexFooter = boContentService.getById("5d8530c950d243e18e57b74190aa2d94");

            res.put("sysMenuList", sysMenuList);
            res.put("logoTitle", logoTitle);
            res.put("indexFooter", indexFooter);
            res.put("state", "200");
            res.put("message", "初始化成功");
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "服务器异常，请重新刷新页面！");
        }

        return res;
    }

    /**
     * 查询文章列表
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getArticleList")
    public Map<String, Object> getArticleList(){
        Map<String, Object> res = new HashMap<>();
        Map<String, Object> params = PageAndParamUtil.getParams();
        try {
            List<Map<String, Object>> articleList = boArticleService.list(params);
            Integer count = boArticleService.getCount(params); //获取总数

            res.put("state", "200");
            res.put("message", "查询文章列表成功");
            res.put("articleList", articleList);
            res.put("count", count);
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "服务器异常，请重新刷新页面！");
        }
        return res;
    }

    /**
     * 跳转文章详情页面
     * @return
     */
    @RequestMapping(value = "articleInfo")
    public String articleInfo(@RequestParam(name = "articleId") String id, Model model){
        model.addAttribute("id", id);
        model.addAttribute("type", "article"); //文章标识
        return PREFIX + "articleInfo";
    }

    /**
     * 根据文章编号查询文章信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getArticleInfo")
    public Map<String, Object> getArticleInfo(@RequestParam(name = "id") String id){
        Map<String, Object> res = new HashMap<>();
        try {
            Map<String, Object> articleInfo = boArticleService.getArticleInfo(id);
            res.put("state", "200");
            res.put("message", "查询文章详情成功");
            res.put("articleInfo", articleInfo);
        }catch (Exception e){
            res.put("state", "500");
            res.put("message", "服务器异常，请重新刷新页面！");
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 根据业务编号和分类查询评论列表
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getCommList")
    public Map<String, Object> getCommList(@RequestParam(name = "id") String id, @RequestParam(name = "classify") String classify){
        Map<String, Object> res = new HashMap<>();
        try {

            //查询文章评论
            Map<String, Object> params = PageAndParamUtil.getParams();
            params.put("serviceId", id);
            params.put("classify", 0);
            List<Map<String, Object>> commList = boCommentService.getList(params);
            //总数
            Integer count = boCommentService.getBaseMapper()
                    .selectCount(new QueryWrapper<BoComment>()
                            .eq("del_flag", 0)
                            .eq("type", 0)
                            .eq("service_id", id)
                            .eq("classify", classify));

            //查询回复总数
            Integer referCount = boCommentService.getBaseMapper()
                    .selectCount(new QueryWrapper<BoComment>()
                            .eq("del_flag", 0)
                            .eq("type", 1)
                            .eq("service_id", id)
                            .eq("classify", classify));

            res.put("state", "200");
            res.put("message", "查询文章评论成功");
            res.put("commList", commList);
            res.put("count", count);
            res.put("referCount", referCount);
        }catch (Exception e){
            res.put("state", "500");
            res.put("message", "服务器异常，请重新刷新页面！");
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 点赞
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updatePraiseNum")
    public Map<String, Object> updatePraiseNum(@RequestParam(name = "id") String id, HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();

        //获取ip地址
        String ipAddress = GetUserIpAddressUtil.getIpAddress(request);
        try {
            boolean flag = boArticleService.updatePraiseNum(id, ipAddress);
            if(flag){
                res.put("state", "200");
                res.put("message", "已赞 >_<");
            }else{
                res.put("state", "500");
                res.put("message", "您今天已点过赞 >_<");
            }
        }catch (Exception e){
            res.put("state", "500");
            res.put("message", "服务器异常点赞失败！");
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 更新阅读数量
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateReadNum")
    public Map<String, Object> updateReadNum(@RequestParam(name = "id") String id){
        Map<String, Object> res = new HashMap<>();
        try{
            BoArticle boArticle = boArticleService.getById(id);
            boArticle.setReadNum(boArticle.getReadNum() + 1);
            boArticleService.updateById(boArticle);
            res.put("state", "200");
            res.put("message", "阅读数量更新成功");
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "服务器异常");
        }
        return res;
    }

    /**
     * 添加文章留言
     * @param boComment
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addComment")
    public Map<String, Object> addComment(BoComment boComment){
        Map<String, Object> res = new HashMap<>();
        try{

            //不输入用户名则默认
            Random random = new Random();
            if("".equals(boComment.getUserName()) || boComment.getUserName() == null){
                boComment.setUserName("匿名用户_" + random.nextInt(99999));
            }

            //回复时，不输入用户名则默认
            if(boComment.getType() == 1 && ("".equals(boComment.getByUserName()) || boComment.getByUserName() == null)){
                boComment.setByUserName("匿名用户_" + random.nextInt(99999));
            }

            //评论内容双引号处理
            boComment.setContent(boComment.getContent().replaceAll("\"",  "'"));

            boComment.preInsert();
            boCommentService.save(boComment);

            res.put("state", "200");
            res.put("message", "已发布>_<");
        }catch (Exception e){
            res.put("state", "500");
            res.put("message", "服务器异常,评论失败>_<");
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 评论点赞
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/commPraise")
    public Map<String, Object> commPraise(@RequestParam(name = "id") String id, HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();

        //获取ip地址
        String ipAddress = GetUserIpAddressUtil.getIpAddress(request);
        try {
            boolean flag = boArticleService.commPraise(id, ipAddress);
            if(flag){
                res.put("state", "200");
                res.put("message", "已赞 >_<");
            }else{
                res.put("state", "500");
                res.put("message", "您今天已点过赞 >_<");
            }
        }catch (Exception e){
            res.put("state", "500");
            res.put("message", "服务器异常点赞失败！");
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 跳转我的文章页面
     * @return
     */
    @RequestMapping(value = "/sendArticle")
    public String sendArticle(){
        return PREFIX + "sendArticle";
    }

    /**
     * 查询导航、LOGO标题、页脚、标签列表
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getSendArticleData")
    public Map<String, Object> getSendArticleData(){
        Map<String, Object> res = new HashMap<>();
        try{
            //查询前台显示导航，并且按创建时间升序排序
            List<SysMenu> sysMenuList = sysMenuService.getBaseMapper()
                    .selectList(new QueryWrapper<SysMenu>()
                            .eq("type", 1)
                            .eq("is_show", 0)
                            .eq("del_flag", 0)
                            .orderByAsc("sort"));

            //查询LOGO标题，编号为：521f1cd04f9d4345af2e62213178d6ac
            BoContent logoTitle = boContentService.getById("521f1cd04f9d4345af2e62213178d6ac");

            //查询页脚，编号为：5d8530c950d243e18e57b74190aa2d94
            BoContent indexFooter = boContentService.getById("5d8530c950d243e18e57b74190aa2d94");

            //查询全部标签列表
            List<BoTag> tagList = boTagService.getBaseMapper().selectList(new QueryWrapper<BoTag>().eq("del_flag", 0));

            res.put("sysMenuList", sysMenuList);
            res.put("logoTitle", logoTitle);
            res.put("indexFooter", indexFooter);
            res.put("tagList", tagList);
            res.put("state", "200");
            res.put("message", "初始化成功");
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "服务器异常，请重新刷新页面！");
        }

        return res;
    }

    /**
     * 保存(保存编辑器上传的图片, 并删除封面图)
     * @param boArticle
     * @param imgName 保存编辑器上传的图片名，用于记录相应的文章图片
     * @param imgSize 对应的图片大小
     * @param boTagArr 标签组
     * @return
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public Map<String, Object> saveData(BoArticle boArticle, String imgName, String imgSize, String boTagArr){
        Map<String, Object> res = new HashMap<>();
        try {
            res = boArticleService.saveData(boArticle, imgName, imgSize, boTagArr);
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "发布失败");
        }
        return res;
    }

    /**
     * 上传封面图
     * @param file
     * @return
     */
    @RequestMapping(value = "/uploadArticleImg")
    @ResponseBody
    public Map<String, Object> uploadArticleImg(MultipartFile file){

        //上传
        Map<String, Object> res = UploadFileUtil.fileUploadToOne(file, UploadURLUtil.U_ARTICLE_IMAGE, false);
        res.put("fileName", UploadURLUtil.U_ARTICLE_IMAGE_PATH + "/" + res.get("fileName"));
        return res;
    }

    /**
     * 文章图片上传
     * @param image
     * @return
     */
    @RequestMapping(value = "/uploadImg")
    @ResponseBody
    public Map<String, Object> uploadImg(MultipartFile[] image){
        Map<String, Object> res = new HashMap<>();
        try {
            List<Map<String, Object>> listMap = UploadFileUtil.fileUploadToMore(image, UploadURLUtil.U_ARTICLE_IMAGE, false);
            List<String> url = new ArrayList<>(); //路径+图片名
            List<String> imgName = new ArrayList<>(); //图片名
            List<String> imgSize = new ArrayList<>(); //图片大小
            for(Map map: listMap){
                if(map.get("state") == "200"){
                    url.add("/" + UploadURLUtil.ARTICLE_IMAGE_PATH + "/" + UploadURLUtil.U_ARTICLE_IMAGE_PATH + "/" + map.get("fileName")); //返回映射路径+图片名
                    imgName.add(map.get("fileName") + ""); //返回图片名
                    imgSize.add(map.get("fileSize") + ""); //返回图片大小
                }
            }
            res.put("state", "200");
            res.put("message", "上传成功");
            res.put("url", url);
            res.put("imgName", imgName);
            res.put("imgSize", imgSize);
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "上传失败");
        }
        return res;
    }

    /**
     * 文件下载
     * @param request
     * @param response
     * @param fileId
     */
    @RequestMapping(value = "/downloadFile")
    @ResponseBody
    public void downloadFile(HttpServletRequest request, HttpServletResponse response, String fileId) throws IOException {
        BoFile boFile = boFileService.getById(fileId);
        File file = new File(UploadURLUtil.FILE + boFile.getFileName());
        if(file.exists()){
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition", "attachment;fileName=" + new String(boFile.getFileOrgname().getBytes("GB2312"),"ISO-8859-1"));
            byte[] buffer = new byte[1024];
            FileInputStream fileInputStream = null;
            BufferedInputStream bufferedInputStream = null;
            try{
                fileInputStream = new FileInputStream(file);
                bufferedInputStream = new BufferedInputStream(fileInputStream);
                OutputStream outputStream = response.getOutputStream();
                int i = bufferedInputStream.read(buffer);
                while (i != -1){
                    outputStream.write(buffer, 0, i);
                    i = bufferedInputStream.read(buffer);
                }
            } catch (Exception e){
                e.printStackTrace();
            } finally {
                bufferedInputStream.close();
                fileInputStream.close();
            }
        }
    }

}
